import subprocess
import time
import datetime
import sys
import socket
import schedule
from my_email import my_email
from xmlparse import *
import configparser

time.sleep(2)

PORT = "5555"

ENCODE = "utf8"

SLEEP_TIME = 60 * 5

ABLE_RUN = True  # 在相应的时间里只执行一次

# 定义配置文件路径
INIT_PATH = r"./config.ini"
config = configparser.ConfigParser()  # 类实例化
config.read(INIT_PATH)
img_package = config['seting']['img_package']
qq = config['seting']['qq']
email1 = my_email(qq)

if sys.platform == "win32":
    ENCODE = "gb2312"


def get_local_ip():
    # s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # s.connect(('8.8.8.8', 80))
    # ip = s.getsockname()[0]
    # s.close()
    ip = socket.gethostbyname(socket.gethostname())
    return ip


def shell_run(str):
    cmd1 = subprocess.Popen(
        str,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        encoding=ENCODE,
    )
    re1, re2 = cmd1.communicate()
    if cmd1.returncode != 0:
        print(re2)
        email1.send_email("程序出错,已退出任务:\n" + re2, "打卡结果")
        exit()
    print(re1)
    time.sleep(0.5)


ip_addr = "192.168.0.8" + ":" + PORT

# adb_device = "-s " + ip_addr
adb_device = ""


def adb_run(img_package: str):
    print("执行任务：{}".format(datetime.datetime.now()))
    # shell_run("adb connect {}".format(ip_addr))
    # shell_run("adb {} shell input keyevent 26".format(adb_device))
    # shell_run("adb {} shell input swipe 540 1300 540 500 100".format(adb_device))
    # <bool name="def_lockscreen_disabled">false</bool> 改为 true；即默认禁止锁屏
    # <integer name="def_screen_off_timeout">6000</integer> 6000改成2147483647，即默认永不灭屏
    # adb shell settings put system screen_off_timeout 2147483647
    # adb shell settings put system def_lockscreen_disabled true
    # 查找当前app的包名和Activity
    # shell_run('adb -s 192.168.0.8:5555 shell dumpsys window | findstr mCurrentFocus')
    shell_run(
        "adb {} shell am start -n com.weaver.emobile7/weaver.fw.com.WelcomeActivity".format(
            adb_device
        )
    )
    time.sleep(5)

    shell_run(
        "adb {} shell uiautomator dump --compressed -p /sdcard/mylinux/mydebian/emobile7/window_dump.xml".format(
            adb_device
        )
    )
    ret = get_current_bounds_xy(
        "/sdcard/mylinux/mydebian/emobile7/window_dump.xml", "取消"
    )
    if not ret is None:
        shell_run("adb {} shell input tap {} {} ".format(adb_device, str(ret[0]), str(ret[1])))
        time.sleep(5)

    shell_run(
        "adb {} shell uiautomator dump --compressed -p /sdcard/mylinux/mydebian/emobile7/window_dump.xml".format(
            adb_device
        )
    )
    ret = get_parent_bounds_xy(
        "/sdcard/mylinux/mydebian/emobile7/window_dump.xml", "工作台"
    )
    if ret is None:
        email1.send_email("未找到工作台xml","打卡失败")
        exit()
    shell_run("adb {} shell input tap {} {} ".format(adb_device, str(ret[0]), str(ret[1])))
    time.sleep(5)

    shell_run("adb {} shell input swipe 500 1270 500 100 1000 ".format(adb_device))
    time.sleep(1)

    shell_run(
        "adb {} shell uiautomator dump --compressed -p /sdcard/mylinux/mydebian/emobile7/window_dump.xml".format(
            adb_device
        )
    )
    ret = get_parent_bounds_xy(
        "/sdcard/mylinux/mydebian/emobile7/window_dump.xml", "考勤打卡"
    )
    if ret is None:
        email1.send_email("未找到考勤打卡xml","打卡失败")
        exit()
    shell_run("adb {} shell input tap {} {} ".format(adb_device, str(ret[0]), str(ret[1])))
    time.sleep(5)

    shell_run(
        "adb {} shell uiautomator dump --compressed -p /sdcard/mylinux/mydebian/emobile7/window_dump.xml".format(
            adb_device
        )
    )
    ret = get_current_bounds_xy(
        "/sdcard/mylinux/mydebian/emobile7/window_dump.xml", "打卡"
    )
    if ret is None:
        email1.send_email("未找到打卡xml","打卡失败")
        exit()
    shell_run("adb {} shell input tap {} {} ".format(adb_device, str(ret[0]), str(ret[1])))
    time.sleep(3)

    shell_run(
        "adb {} shell screencap -p /sdcard/mylinux/mydebian/emobile7/screen.png".format(
            adb_device
        )
    )
    shell_run("adb {} shell am force-stop com.weaver.emobile7".format(adb_device))
    shell_run("adb {} shell am start -n {}".format(adb_device, img_package))
    # shell_run(
    #     "adb {} shell am start -n com.termux/com.termux.app.TermuxActivity".format(
    #         adb_device
    #     )
    # )
    # shell_run(
    #     "adb {} shell am start -n com.vivo.gallery/com.android.gallery3d.vivo.NewPageActivity".format(
    #         adb_device
    #     )
    # )
    # shell_run(
    #     "adb {} shell am start -n com.hihonor.photos/com.huawei.gallery.app.GalleryMain".format(
    #         adb_device
    #     )
    # )
    email1.send_email("打卡结果", "打卡结果", "/root/mydebian/emobile7/screen.png")

    # shell_run("adb {} shell input keyevent 26".format(adb_device))


# 执行任务
if __name__ == "__main__":
    schedule.every().day.at("08:15:00").do(adb_run,img_package=img_package)
    schedule.every().day.at("12:01:00").do(adb_run,img_package=img_package)
    schedule.every().day.at("13:45:00").do(adb_run,img_package=img_package)
    schedule.every().day.at("17:31:00").do(adb_run,img_package=img_package)

    # 循环检查时间，直到结束时间
    while True:
        schedule.run_pending()
        current_time = datetime.datetime.now().strftime("%H:%M")
        print(current_time)
        time.sleep(SLEEP_TIME)
